package com.ly.hotel.timetask;

import java.lang.ref.WeakReference;
import java.util.TimerTask;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.ly.hotel.common.MyApplication;
import com.ly.hotel.service.SPABackService;
import com.ly.hotel.service.SPAService;


import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class HeartbeatTimerTask extends TimerTask{
	private ThisHandler handler = new ThisHandler(this);
	@Override
	public void run() {
		// TODO Auto-generated method stub
		Message message = new Message();
        message.what=1;
        handler.sendMessage(message);
	}

	private static class ThisHandler extends Handler {
		private WeakReference<HeartbeatTimerTask> wrActivity;

		public ThisHandler(HeartbeatTimerTask activity) {
			wrActivity = new WeakReference<HeartbeatTimerTask>(activity);
		}

		@Override
		public void handleMessage(Message message) {
			super.handleMessage(message);
            if(message.what==1) {
            	try {
					String url = MyApplication.getHost() + SPAService.PROJECT + "/api/heartbeat.json?mac=" + MyApplication.getMAC();
					
					StringRequest  stringRequest = new StringRequest(Request.Method.GET, url, 
			                 new Response.Listener<String>() {  
			                     @Override  
			                     public void onResponse(String response) {  
			                    	 Log.i("heart", "发送心跳包完成:" + response);
			                     }  
			                 }, new Response.ErrorListener() {  
			                     @Override  
			                     public void onErrorResponse(VolleyError error) {  
			                    	 Log.e("heart", "发送心跳包失败." + error.getMessage()); 
			                     }  
			                 }); 
					stringRequest.setTag("heart");
					stringRequest.setShouldCache(false);
					SPABackService.mQueue.add(stringRequest);
				} catch (Exception e) {
					Log.e("heart", "SPAService.heartbeat:" + e.getMessage());
				}
            }
		}
	}
}
